package com.yonyou.crm.common.base;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.http.client.CrmHttpClient;
import com.yonyou.crm.common.http.client.CrmResponse;
import com.yonyou.crm.common.rest.constant.HttpCodeConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.customer.entity.CustomerIdentifyDetailVO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.cum.customer.rmitf.ICustomerRmService;

public class EnterpriseBaseCtrl {
	
	@Autowired
	protected ICustomerRmService service;
	
	protected static final String ApiBaseDir = "https://api.yonyoucloud.com/apis/";
	protected static final String ApiCode = "17eb5ca0f9624a3e9cdf6cbd9fbf5de8";
	
	//获取请求头参数
	private Map<String, String> getApiHeader() {
		Map<String, String> header = new HashMap<String, String>();
		header.put("authoration", "apicode");
		header.put("apicode", ApiCode);
		return header;
	}
	
	/**
	 * 企业信息按名称查询
	 * @param request
	 */
	public Object getEnteInfoByName(HttpServletRequest request) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String name = (String) paramObj.get("name");	//企业名称
		if (name == null || StringUtils.isBlank(name)) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "企业名称不能为空");
		}
		String size  = paramObj.get("size").toString();  //返回结果数量（默认20）
		if (size == null || size.equals("0")) {
			size = "20";
		}
		
		String url = ApiBaseDir + "yonyoucloudresearch/enterpriseSearch/queryAutoComplete";//请求接口地址
		Map<String, String> params = new HashMap<String, String>();//请求参数
		params.put("keyword", name);
		params.put("size", size);
		CrmResponse cResp = CrmHttpClient.get(url, params, getApiHeader());
		
		JSONObject respData = JSONObject.fromObject(cResp.getData());
		if ((HttpCodeConstant.OK+"").equals(respData.get("state"))) {
			JSONArray dataArray = (JSONArray)respData.get("details");
			List<Map<String, String>> companyList = JSONArray.toList(dataArray, new HashMap<String, String>(), new JsonConfig());
			List<Map<String, String>> data = new ArrayList<>();
			if ((companyList != null) && (companyList.size() > 0)){
				for(int i = 0; i < companyList.size(); i++) {
					Map<String, String> company = companyList.get(i);
					Map<String, String> companyInfo = new HashMap<>();
					companyInfo.put("companyname", company.get("corpname"));
					companyInfo.put("companyid", company.get("companyid"));
					data.add(companyInfo);
				}
			}
			return data;
		}
		else {
			String message = getErrorMessage(respData);
			throw new CrmMessageException(PCCodeConstant.ServerError, message);
		}
		
	}
	
	/**
	 * 企业信息全词查询
	 * @param request
	 * @return
	 * @throws CrmMessageException
	 */
	public Object getEnteInfoByFullName(String fullName) throws CrmMessageException {
		Map<String, String> company = getEnteInfoByfullname(fullName);
		List<CustomerIdentifyDetailVO> list = getIdentifyDetail(company);
		return list;
	}
	
	/**
	 * 企业信息全词查询
	 * @param request
	 * @return
	 * @throws CrmMessageException
	 */	
	public Map<String, String> getEnteInfoByfullname(String fullName) throws CrmMessageException {
		if (fullName == null || StringUtils.isBlank(fullName)) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "企业名称不能为空");
		}
		String url = ApiBaseDir + "yonyoucloudresearch/enterpriseSearch/queryFull";//请求接口地址
		Map<String, String> param = new HashMap<String, String>(); //请求参数
		param.put("fullname", fullName);
		CrmResponse cResp = CrmHttpClient.get(url, param, getApiHeader());
		
		JSONObject respData = JSONObject.fromObject(cResp.getData());
		if ((HttpCodeConstant.OK+"").equals(respData.get("state"))) {
			JSONArray dataArray = (JSONArray)respData.get("details");
			Map<String, String> company = (Map<String, String>)dataArray.get(0);
			return company;
		} 
		else {
			String message = getErrorMessage(respData);
			throw new CrmMessageException(PCCodeConstant.ServerError, message);
		}
	}
	
	
	/**
	 * 企业信息精确查询
	 * @param id
	 * @return
	 * @throws CrmMessageException
	 */	
	public Map<String, String> getEnteInfoById(String id) throws CrmMessageException {
		if (StringUtils.isBlank(id)) {
			throw new CrmMessageException("企业id不能为空");
		}
		String url = ApiBaseDir + "yonyoucloudresearch/enterpriseSearch/queryDetail";//请求接口地址
		Map<String, String> param = new HashMap<String, String>(); //请求参数
		param.put("id", id);
		CrmResponse cResp = CrmHttpClient.get(url, param, getApiHeader());
		
		JSONObject respData = JSONObject.fromObject(cResp.getData());
		if ((HttpCodeConstant.OK+"").equals(respData.get("state"))) {
			JSONArray dataArray = (JSONArray)respData.get("details");
			Map<String, String> company = (Map<String, String>)dataArray.get(0);
			return company;
		} 
		else {
			String message = getErrorMessage(respData);
			throw new CrmMessageException(PCCodeConstant.ServerError, message);
		}
	}
	
	/**
	 * 企业信息全词查询
	 * @param request
	 * @return
	 * @throws CrmMessageException
	 */	
	public Map<String, String> getEnteInfoByfullname(HttpServletRequest request) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String name = (String) paramObj.get("name");	//企业名称
		if (name == null || StringUtils.isBlank(name)) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "企业名称不能为空");
		}
		String url = ApiBaseDir + "yonyoucloudresearch/enterpriseSearch/queryFull";//请求接口地址
		Map<String, String> param = new HashMap<String, String>(); //请求参数
		param.put("fullname", name);
		CrmResponse cResp = CrmHttpClient.get(url, param, getApiHeader());
		
		JSONObject respData = JSONObject.fromObject(cResp.getData());
		if ((HttpCodeConstant.OK+"").equals(respData.get("state"))) {
			JSONArray dataArray = (JSONArray)respData.get("details");
			Map<String, String> company = (Map<String, String>)dataArray.get(0);
			return company;
		} 
		else {
			String message = getErrorMessage(respData);
			throw new CrmMessageException(PCCodeConstant.ServerError, message);
		}
	}
	
	/**
	 * 根据查询结果状态返回错误信息
	 * @param respData
	 * @return String
	 */
	private String getErrorMessage(JSONObject respData) {
		String message = "";
		if (respData.get("state").equals("404")) {
			message ="找不到目标企业";
		} else {
			message = "获取远程数据失败";
		}
		return message;
	}
	
	/**
	 * 企业信息精确查询
	 * @param id
	 * @return
	 * @throws CrmMessageException
	 */	
	public Object getEnteInfoByCompanyId(String id) throws CrmMessageException {
		Map<String, String> company = getEnteInfoById(id);
		List<CustomerIdentifyDetailVO> list = getIdentifyDetail(company);
		return list;
	}
	
	/**
	 * 企业信息全词查询
	 * @param request
	 * @return
	 * @throws CrmMessageException
	 */
	public Object getEnteInfoByFullName(HttpServletRequest request) throws CrmMessageException {
		Map<String, String> company = getEnteInfoByfullname(request);
		List<CustomerIdentifyDetailVO> list = getIdentifyDetail(company);
		return list;
	}
	
	/**
	 * 企业信息格式化
	 * @param company
	 * @return
	 */
	private List<CustomerIdentifyDetailVO> getIdentifyDetail(Map<String, String> company) {
		List<CustomerIdentifyDetailVO> list = new ArrayList<>();
		CustomerIdentifyDetailVO data;
		data = new CustomerIdentifyDetailVO("verifyFullname","公司名称",company.get("corpname") != null ? company.get("corpname") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("website","公司官网",company.get("website") != null ? company.get("website") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("street","地址",company.get("address") != null ? company.get("address") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("creditCode","统一社会信用代码",company.get("creditcode") != null ? company.get("creditcode") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("bizRegno","工商注册号",company.get("gongsh") != null ? company.get("gongsh") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("orgCode","组织机构代码",company.get("orgcode") != null ? company.get("orgcode") : "");
		list.add(data); 
		data = new CustomerIdentifyDetailVO("state","经营状态",company.get("state") != null ? company.get("state") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("type","公司类型",company.get("type") != null ? company.get("type") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("regtime","注册时间",company.get("regtime") != null ? company.get("regtime") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("legalRepresent","法人",company.get("proxyer") != null ? company.get("proxyer") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("regCapital","注册资本",company.get("money") != null ? company.get("money") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("businessTerm","营业期限",company.get("onlinetime") != null ? company.get("onlinetime") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("regOrg","注册机关",company.get("regpart") != null ? company.get("regpart") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("bizScope","经营范围",company.get("fieldrange") != null ? company.get("fieldrange") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("industry","行业",company.get("industry") != null ? company.get("industry") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("email","邮箱",company.get("email") != null ? company.get("email") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("tel","联系电话",company.get("phone") != null ? company.get("phone") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("taxpayerNo","纳税人识别号",company.get("taxNumber") != null ? company.get("taxNumber") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("hasunify","是否三证合一",company.get("hasUnify") != null ? company.get("hasUnify") : "");
		list.add(data);
		data = new CustomerIdentifyDetailVO("remark","公司简介",company.get("shortcut") != null ? company.get("shortcut") : "");
		list.add(data);
		return list;
	}
	
	/**
	 * 企业审核
	 * @param id
	 * @param request
	 * @return
	 * @throws CrmMessageException
	 */	
	public Object identification(String id, HttpServletRequest request)
			throws CrmMessageException {
		if (StringUtils.isBlank(id)) {
			throw new CrmMessageException("客户id不能为空");
		}
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String status = (String) paramObj.get("status"); // 认证状态（“Y”表示认证，“N”表示取消认证）
		CustomerVO customer = getCustomerVO(request);
		if (customer == null) {
			throw new CrmMessageException("客户实体转换失败");
		}
		customer.setId(Long.valueOf(id));
		if ("Y".equals(status)) {
			customer.setIsIdentified(1);
			Object companyId = paramObj.get("companyid");
			if (companyId != null) {
				String companyIdStr = String.valueOf(companyId);
				if (StringUtils.isBlank(companyIdStr)) {
					throw new CrmMessageException("公司id不能为空");
				}
				customer.setVerifyId(companyIdStr);
			}
			customer = service.identify(customer);
		} else if ("N".equals(status)) {
			customer.setIsIdentified(0);
			customer.setVerifyId("");
			customer = service.cancelIdentify(customer);
		} else {
			throw new CrmMessageException("认证状态不正确");
		}
		return ResponseUtil.getObject(customer);
	}
	
	private CustomerVO getCustomerVO(HttpServletRequest request) {
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("salesVOs", CustomerSalesVO.class);
		return RequestUtil.getVO(request, CustomerVO.class, fieldClassMap);
	}
	
	/**
	 * 根据客户id获取审核信息
	 * @param id
	 * @param request
	 * @param response
	 * @throws CrmMessageException
	 */
	public Map<String, Object> getEnteInfoByCustomerId(String id, HttpServletRequest request) throws CrmMessageException {
		if (StringUtils.isBlank(id)) {
			throw new CrmMessageException("客户id不能为空");
		}
		CustomerVO customer = service.getDetail(Long.valueOf(id));
		String companyId = customer.getVerifyId();
		Integer identify = customer.getIsIdentified();
		if (identify != null && identify == 1) {
			Map<String, Object> res = new HashMap<>();
			Object list = getEnteInfoByCompanyId(companyId);
			res.put("data", list);
			res.put("companyid", id);
			return res;
		}
		return new HashMap<String, Object>();
	}
	
	/**
	 * 获取公司是否已认证标识
	 * @throws CrmMessageException 
	 */
	public boolean getIdentifyFlag(Map<String, Object> paraMap) throws CrmMessageException {
		boolean identifyFlag = false;
		identifyFlag = service.getIdentifyFlag(paraMap);
		return identifyFlag;
	}
	
	/**
	 * 根据公司Id获取公司是否已认证标识
	 * @param companyid
	 * @return
	 * @throws CrmMessageException
	 */
	public boolean getIdentifyFlagByCompanyId(String companyid) throws CrmMessageException {
		boolean identifyFlag = false;
		if (StringUtils.isBlank(companyid)) {
			throw new CrmMessageException("公司Id不能为空");
		}
		Map<String, Object> paraMap = new HashMap<>();
		paraMap.put("verifyId", companyid);
		identifyFlag = getIdentifyFlag(paraMap);
		return identifyFlag;
	}
	
}
